<?php
namespace Payment\Controller;
use Think\Controller;
/*
      首页
*/
class InitController extends Controller {

    /**
     * 支付通知返回
     * @return string   
     */
    public function order_notify(){
		
        $re_url = explode("/",$_SERVER['REQUEST_URI']);
        
        $payment_type = strtolower($re_url[3]);
        \Think\Log::write($payment_type,'pay_notify_start');

        //引用对应的支付模块
        Vendor("Payment.{$payment_type}.notify");
        
        \Think\Log::write($payment_type,'pay_notify_vender');

        //每个支付模块的接收数据都不一样，独立在对应支付模块的notify中 getpostdatainfo()获取返回参数， pay_sn 为支付单号， flowsn 为流水号
        $postdata = getpostdatainfo();//获取返回信息
        \Think\Log::write(json_encode($postdata),'pay_notify_getpostdatainfo');

        if(empty($postdata)){
            exit('error');
        }

        $pay_sn = $postdata['pay_sn'];
        $flowsn = $postdata['flowsn'];

        $payloginfo = M('User_paysn')->alias("ps")
			->join("left join __PAY_LOG__ as pl on ps.id = pl.pay_sn_id")
			->where("ps.pay_sn = '{$pay_sn}' and pl.status = '0' ")
			->field("pl.order_id,pl.uid,pl.module,pl.id as paylog_id")->find();
        
        \Think\Log::write(json_encode($payloginfo),'pay_notify_payloginfo');

        if(empty($payloginfo)){
            exit('error');
        }
		
		if($payment_type == 'wxpay'){
			$payment_type = 'wx_pay';
		}
		
		//搜索支付方式
		$paymentcontent = M('Options')->where(array('option_name'=>strtolower($payment_type)))->getField('option_value');
		
		if(empty($paymentcontent)){
			exit("商家没有开通支付");
		}
		$paymentinfo = unserialize($paymentcontent); 
		
       // $payment = C('PAYMENT_SETTING');
        //$paymentinfo = $payment[$payment_type];
		
        //$payment = M('Payment')->where(array('type'=>$payment_type))->getField('content');
        
        //$paymentinfo = unserialize($payment);

        // Vendor("Payment.{$payment_type}.notify"); 在这个文件里面，返回true or false
		
	
        $payCheck = checkReturn($paymentinfo);

        \Think\Log::write($payCheck,'pay_notify_checkReturn');
      
        if(!$payCheck){
			\Think\Log::write('payCheck返回false','error_1');
            exit('error');
        }

        $fans_id    = $payloginfo['uid'];
        $module     = $payloginfo['module'];
        $ordersn    = $pay_sn;
	
	
        $Rmodule = ucfirst(strtolower($module));
        $order_info = R($Rmodule."/Payment/ReturnPaymentAction",array($payloginfo['order_id'],$ordersn));
		
		if(empty($order_info)){
			\Think\Log::write('order_info空了，没有虚拟订单信息','error_1');
			exit('error');
		}

        $order_id     = $order_info['id'];
        $price        = $order_info['price'];
		
		//支付记录
		$pay_array     = M('PayLog')->where("order_id = {$order_id}")->find();
		

		if(empty($pay_array)){
			\Think\Log::write('pay_array空了，没有支付记录','error_1');
			exit('error');
		}
		
        \Think\Log::write("支付订单状态改变",'pay_notify');
		
		M('PayLog')->where(array('id'=>$pay_array['id']))->save(array("status"=>'1'));
        M('UserOrder')->where(array('id'=>$order_id))->save(array("status"=>'1'));
    
        //============== 佣金计算  ===============//
        $parent_id = M('UserRelationship')->where(array('subordinate_user'=>$fans_id))->getField('user_id');
        $this->parentReturnCommission($parent_id,$order_id,$price,$fans_id);
		
		//计算是否有总代，有就获取20%的佣金
		$this->super_agent_commission($fans_id,$price,$order_id);
		
        //============== 佣金计算end  ===============//
		
		//支付号
		$pay_sn_array  = M('User_paysn')->where("id = {$pay_array['pay_sn_id']}")->find();
		//升级信息
		$upgrade_array = M('User_upgrade_log')->where(array('pay_sn'=>$pay_sn_array['pay_sn']))->find();
		
		\Think\Log::write(json_encode($upgrade_array) , 'upgrade_array_96');
		
		//商家升级记录(返回)
		$upgrade_data = array(
			'pay_time'=>NOW_TIME,
			'pay_flow'=>$flowsn,
			'is_paid'=>1
		);

		$judge = M('User_upgrade_log')->where(array('id'=>$upgrade_array['id'],'pay_sn'=>$pay_sn_array['pay_sn']))->save($upgrade_data);

		if(!$judge){
			\Think\Log::write("支付失败！执行SQL：" . M('User_upgrade_log')->getLastSql() ,'pay_error');
			die('失败');
		}

		$user_info = M('User')->where(array('id'=>$upgrade_array['user_id']))->find();

		//生成会员期限
		$user_month = "+{$upgrade_array['valid_time']} month";

		//当非会员升级会员时
		if(empty($user_info['valid_time'])){
			$time = NOW_TIME;
		}else{
			$time = $user_info['valid_time'];
		}
		
		//延长会员期
		$user_month = strtotime($user_month, $time);
		$data_time_string = "会员有效期:".date("Y/m/d",$user_month);

		if($upgrade_array['valid_time'] == '0'){
			$user_month = '0';
			$data_time_string = "会员有效期:终身有效";
		}

		//成功后升级
		M('User')->where(array('id'=>$user_info['id']))->save(array('level'=>$upgrade_array['upgrade_level'],'valid_time'=>$user_month));

		if($upgrade_array['pay_type'] == '1'){
			$text_pay = '微信';
		}else if($upgrade_array['pay_type'] == '2'){
			$text_pay = '支付宝';
		}

		$data_log = array(
			'createtime'=>NOW_TIME,
			'order_id'=>$order_id,
			'remark'=>"订单编号：{$order_id};支付方式是:{$text_pay};平台流水号:{$flowsn};支付金额：{$upgrade_array['pay_amount']};会员id:{$user_info['id']};会员手机：{$user_info['mobile']};原等级：{$user_info['level']};升级等级{$upgrade_array['upgrade_level']};{data_time_string}"
		);

		M('Up_level_log')->add($data_log);
		
		//支付升级发送邮件
		$content = "用户名：{$user_info['username']},手机号码：{$user_info['mobile']};升级支付金额({$upgrade_array['pay_amount']}元);{$data_time_string},<a href='".U('admin/Index/index','','',true)."' target='_blank'>立即登录查看</a>";
				
		//发送邮件
		@send_mail($this->opt['send_mail'],'升级支付','升级支付',$content);
		
		\Think\Log::write(M()->getLastSql() , 'over_ok');
        
        exit('success');
    }


    /**
     * 记录3级佣金
     * @parent_id   父的ID
     * @order_id    订单主键id
     * @price     订单金额
     * @user_id   支付的人
     */
    private function parentReturnCommission($parent_id, $order_id,$price,$user_id){
		\Think\Log::write("未来这里了"  ,'ok_im_here');
		$UserRelationshipModel = M('UserRelationship');
		//第一级
		$level_1_user_info = $UserRelationshipModel->where(array('subordinate_user'=>$user_id))->field('subordinate_user,user_id')->find();
		
		\Think\Log::write(json_encode($level_1_user_info)  ,'level_1_user_info');
			
		if(empty($level_1_user_info)){
			return false;
		}
		
		//消息模板通知
		import('Vendor.Wechat.access');
		$wechat = new \WechatAccess();
		
		//佣金规则
		$commission_rule = M('CommissionRule')->find();
		
		if(empty($commission_rule)){
			return false;
		}
		
		//计算第一级佣金
		$UserSpreadIncomeModel = M('UserSpreadIncome');
		if(!empty($commission_rule['level_1_brokerage'])){
			$commission = ($commission_rule['level_1_brokerage'] + 0)/100 * ($price * 100); //单位分
			$add = array(
				'spreader'=>$level_1_user_info['user_id'], 
				'register'=>$user_id,
				'commission'=>$commission,
				'createtime'=>NOW_TIME,
				'remark'=>'用户'.$user_id.'升级，user_order主键'.$order_id.'，升级费用'. $price .'，佣金规则level_1_brokerage佣金点数：'.$commission_rule['level_1_brokerage'] . '，获得佣金：'.$commission/100,
			);
			$UserSpreadIncomeModel->add($add);
			
			//level_2_user_info['user_id']，推广者
			//commssion 佣金
			//$user_id   注册者
		
			//通知上级
			$wechat->sendwx_inform($level_1_user_info['user_id'],$user_id,$commission/100,$price);
				
			  //消息通知
			  $type = 2;
			  $add['parent_id'] = $level_1_user_info['user_id'];
			  information_content($user_id,$type,$add);
			
			
		}
		
		//第二级
		$level_2_user_info = $UserRelationshipModel->where(array('subordinate_user'=>$level_1_user_info['user_id']))->field('subordinate_user,user_id')->find();

		\Think\Log::write(json_encode($level_2_user_info)  ,'level_2_user_info');		
	
		if(empty($level_2_user_info)){
			return false;
		}
		
		if(!empty($commission_rule['level_2_brokerage'])){
			$commission = ($commission_rule['level_2_brokerage'] + 0)/100 * ($price * 100); //单位分
			$add = array(
				'spreader'=>$level_2_user_info['user_id'], 
				'register'=>$user_id,
				'commission'=>$commission,
				'createtime'=>NOW_TIME,
				'remark'=>'用户'.$user_id.'升级，user_order主键'.$order_id.'，升级费用'. $price .'，佣金规则level_2_brokerage佣金点数：'.$commission_rule['level_2_brokerage'] . '，获得佣金：'.$commission/100,
			);
			$UserSpreadIncomeModel->add($add);
			
			//level_2_user_info['user_id']，推广者
			//commssion 佣金
			//$user_id   注册者
			
			//通知上级
			$wechat->sendwx_inform($level_2_user_info['user_id'],$user_id,$commission/100,$price);
			
			
			 //消息通知
			 $type = 2;
			 $add['parent_id'] = $level_2_user_info['user_id'];
			 information_content($user_id,$type,$add);
			
		}
		
		//第三级
		$level_3_user_info = $UserRelationshipModel->where(array('subordinate_user'=>$level_2_user_info['user_id']))->field('subordinate_user,user_id')->find();
	
	\Think\Log::write(json_encode($level_3_user_info)  ,'level_3_user_info');	
		
		if(empty($level_3_user_info)){
			return false;
		}
		
		if(!empty($commission_rule['level_3_brokerage'])){
			$commission = ($commission_rule['level_3_brokerage'] + 0)/100 * ($price * 100); //单位分
			$add = array(
				'spreader'=>$level_3_user_info['user_id'], 
				'register'=>$user_id,
				'commission'=>$commission,
				'createtime'=>NOW_TIME,
				'remark'=>'用户'.$user_id.'升级，user_order主键'.$order_id.'，升级费用'. $price .'，佣金规则level_3_brokerage佣金点数：'. $commission_rule['level_3_brokerage'] . '，获得佣金：'.$commission/100,
			);
			$UserSpreadIncomeModel->add($add);
			
			//level_2_user_info['user_id']，推广者
			//commssion 佣金
			//$user_id   注册者
			
			//通知上级
			$wechat->sendwx_inform($level_3_user_info['user_id'],$user_id,$commission/100,$price);
			
			//消息通知
			$type = 2;
			
			$add['parent_id'] = $level_3_user_info['user_id'];
			information_content($user_id,$type,$add);
			
		} 		
    }
	
	/*
	*计算总代佣金
	*@param int $fans_id 当前会员id
	*@param float $price 支付金额
	*@param int $order_id 订单id
	*@return mixed 空的返回值
	*/
	private function super_agent_commission($fans_id,$price,$order_id){
		//佣金规则
		$commission_rule = M('CommissionRule')->find();
		if(empty($commission_rule['agency'])){
			return false;
		}
		$spreader_id = spread_all($fans_id);
		$UserSpreadIncomeModel = M('UserSpreadIncome');
		if(!empty($spreader_id)){
			//总代佣金
			$commission = $commission_rule['agency']/100 * ($price * 100); //单位分
			$add = array(
				'spreader'=>$spreader_id, 
				'register'=>$fans_id,
				'commission'=>$commission,
				'createtime'=>NOW_TIME,
				'is_all'=>1,
				'remark'=>'用户'.$fans_id.'升级;由于'.$spreader_id.'用户是总代，订单主键id:'.$order_id.'升级费用'.$price.';获得佣金'.$commission/100,
			);
			$UserSpreadIncomeModel->add($add);
			//消息通知
			$type = 2;
			//信息中心
			$add['parent_id'] = $spreader_id;
			information_content($fans_id,$type,$add);
			//消息模板通知
			import('Vendor.Wechat.access');
			$wechat = new \WechatAccess();
			//通知上级
			$wechat->sendwx_inform($spreader_id,$fans_id,$commission/100,$price,1);
			
		}
	}

}